<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="queryId" placeholder="商品分类编号" style="width: 200px; margin:5px 0 5px 0;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="queryName" placeholder="商品分类名称" style="width: 200px; margin: 5px 0 5px 0;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="queryRecommend" placeholder="是否推荐" clearable style="width: 160px; margin: 5px 0 5px 0;" class="filter-item">
        <el-option v-for="item in recommendOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="queryStats" placeholder="是否上架" clearable style="width: 150px; margin: 5px 0 5px 0;" class="filter-item">
        <el-option v-for="item in statsOptions" :key="item" :label="item" :value="item" />
      </el-select>

      <el-date-picker v-model="queryDate" style="width: 300px; margin:5px 0 5px 0;" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="优惠券开始日期" end-placeholder="优惠券结束日期" />

      <el-button class="filter-item" style="margin: 5px 0 5px 0;" type="primary" icon="el-icon-search" @click="handleFilter" />
      <br>
    </div>

    <el-table ref="multipleTable" v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column align="center" label="商品编号" width="120">
        <template slot-scope="scope">
          {{ scope.row.product_id }}
        </template>
      </el-table-column>
      <el-table-column label="商品名称" width="240" align="center">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="商品分类名称" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.category_name }}
        </template>
      </el-table-column>
      <el-table-column label="商品主图" width="120" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.pic"  min-width="70" height="70" />
        </template>
      </el-table-column>
      <el-table-column label="推荐" width="120" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.recommend | recommendCssFilter">
            {{ row.recommend | recommendFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.stats | statusCssFilter">
            {{ row.stats | statusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品售价" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券金额" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.coupon_price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="今日销量" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.today_sales }}</span>
        </template>
      </el-table-column>
      <el-table-column label="月销量" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sales }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券总数量" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.coupon_num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="佣金比例" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.rate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="佣金" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.commission }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动类型" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.activity_type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券开始时间" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.coupon_start_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券结束时间" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.coupon_end_time }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="currentPage" :limit.sync="pageSize" @pagination="fetchData({})" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"  :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:30px;">

        <el-form-item label="是否推荐">
          <el-select v-model="temp.recommend" class="filter-item" placeholder="是否推荐">
            <el-option v-for="(item, idx) in recommendOptions" :key="item" :label="item" :value="idx" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否上架">
          <el-select v-model="temp.stats" class="filter-item" placeholder="是否上架">
            <el-option v-for="(item, idx) in statsOptions" :key="item" :label="item" :value="idx" />
          </el-select>
        </el-form-item>

        <el-form-item  label="广告图片">
          <el-upload
              action="/common/common/common/upload"
              list-type="picture-card"
              accept=".jpg,.jpeg,.png,.gif"
              :multiple="false"
              :limit="1"
              :data="tbkImagesObj"
              :on-preview="handleTbkPictureCardPreview"
              :file-list="tbkImagesArr"
              :on-remove="handleTbkPicRemove"
              :before-remove="handleTbkPicBeforeRemove"
              :on-success="handleTbkPicUploadResult"
              :on-error="handleUploadError"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-input v-model="temp.pic" type="hidden" />
          <el-dialog :visible.sync="dialogTbkImageVisible" size="tiny">
            <img width="100%" :src="dialogTbkImageUrl" alt="">
          </el-dialog>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getList,editTbkproduct } from '@/api/tbkProduct'
  import { deleteImage } from '@/api/alibabaProduct'
  import Pagination from '@/components/Pagination'

  export default {
    components: { Pagination },
    filters: {
      recommendFilter(recommend) {
        const recommendMap = {
          1: '推荐',
          0: '不推荐'
        }
        return recommendMap[recommend]
      },
      recommendCssFilter(recommend) {
        const recommendMap = {
          1: 'success',
          0: 'info'
        }
        return recommendMap[recommend]
      },
      statusFilter(status) {
        const statusMap = {
          0: '下架',
          1: '上架'
        }
        return statusMap[status]
      },
      statusCssFilter(status) {
        const statusMap = {
          1: 'success',
          0: 'warn'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        hidden: false,
        listLoading: true,
        // 翻页相关数据 当前页，每页显示条数，排序方式，排序字段，符合条件的搜索结果数，搜索结果
        currentPage: 1,
        pageSize: 10,
        sort: 'desc',
        order: 'product_id',
        total: 0,
        list: [],
        queryId: '',
        queryName: '',
        queryStats: '',
        queryRecommend:'',
        queryParent: '',
        querySubParent: '',
        queryLeafParent: '',
        queryDate: '',
        sortBy: '',
        dialogStatus:'',
        // 弹出层数据
        // 是否隐藏弹出层
        dialogFormVisible: false,
        // 弹出层状态(创建、编辑)
        textMap: {
          update: '编辑',
          create: '创建'
        },
        // 临时数据
        temp: {
          id: undefined,
          name: '',
          type: '',
          status: '',
          past_time: '',
          ad_addr_type: '',
          ad_addr: '',
          img: '',
          order: ''
        },
        // 搜索条件相关数据
        importanceOptions: [1, 2, 3],
        statsOptions: ['下架', '上架'],
        recommendOptions: ['不推荐','推荐'],
        showReviewer: false,
        pickerOptions: {
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近3天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        // 下载的loading
        downloadLoading: false,
        downloadData: [],
        changeFlag: false,
        tbkImagesObj: {},
        tbkImagesArr: [],
        dialogTbkImageUrl: '',
        dialogTbkImageVisible: false,

      }
    },
    mounted() {},
    created() {
      this.getParent(0, 'topParent')
      this.fetchData()
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleFilter() {
        this.currentPage = 1
        this.fetchData()
      },

      handleDownload() {
        this.downloadLoading = true
        this.downloadLoading = false
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const param = {
              product_id: this.temp.product_id,
              recommend: this.temp.recommend,
              stats: this.temp.stats,
              pic: this.temp.pic,
            }
            editTbkproduct(param).then(() => {
              this.$notify({
                title: '编辑成功',
                type: 'success',
                message: '商品编辑成功',
                duration: 2000
              })
              this.fetchData()
              this.dialogFormVisible = false
            }).catch(error => {
              this.$notify({
                title: '编辑失败',
                type: 'error',
                message: error.errmsg,
                duration: 2000
              })
            })
          }
        })
      },
      formatJson(filterVal) {
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row)
        console.log(this.temp);

        this.tbkImagesArr = [{
          name: this.temp.title,
          url: this.temp.pic,
          id: this.temp.id
        }]

        this.tbkImagesObj = {
          id: this.temp.id,
          type: 'tbk_image'
        }

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleModifyStatus(row, value) {},
      getParent(parent, vc) {
        let isLeaf = false
        const param = {
          sort: this.sort,
          order: this.order,
          page: this.currentPage,
          page_size: 9999
        }


      },
      fetchData() {
        this.listLoading = true

        const param = {
          sort: 'desc',
          order: 'product_id',
          page: this.currentPage,
          page_size: this.pageSize
        }
        if (this.queryId !== '') {
          param.product_id = this.queryId
        }
        if (this.queryName !== '') {
          param.name = this.queryName
        }
        if (this.queryStats !== '') {
          this.statsOptions.map((item, idx) => {
            if (this.queryStats === item) {
              param.stats = idx
            }
          })
        }
        if (this.queryRecommend !== '') {
          this.recommendOptions.map((item, idx) => {
            if (this.queryRecommend === item) {
              param.recommend = idx
            }
          })
        }
        if (this.queryDate !== '' && this.queryDate !== null) {
          param.coupon_start_time = this.queryDate[0].toLocaleDateString() + ' ' + this.queryDate[0].toTimeString().split(' ')[0]
          param.coupon_end_time = this.queryDate[1].toLocaleDateString() + ' ' + this.queryDate[1].toTimeString().split(' ')[0]
        }

        getList(param).then(response => {
          const { data, meta } = response
          this.list = data
          this.listLoading = false
          this.currentPage = parseInt(meta.current_page)
          this.total = parseInt(meta.total)
        }).catch(() => {
          this.listLoading = false
          this.list = []
        })
      },
      // 图片上传失败
      handleUploadError(err, file, fileList) {
        const resp = JSON.parse(err.message)
        this.$notify({
          title: '图片上传失败',
          type: 'error',
          message: resp.errmsg,
          duration: 2000
        })
      },
      // 广告图片
      handleTbkPictureCardPreview(file) {
        this.dialogMainImageUrl = file.url
        this.dialogMainImageVisible = true
      },
      handleTbkPicRemove(file, fileList) {
        console.log(file)
        console.log(fileList)
        const param = {
          url: this.temp.pic,
          type: 'tbk_image',
          id: this.temp.id
        }
        console.log(param)
        deleteImage(param).then(() => {
          this.$notify({
            title: '图片删除成功',
            type: 'success',
            message: '图片删除成功',
            duration: 2000
          })
        }).catch(error => {
          this.$notify({
            title: '图片删除失败',
            type: 'error',
            message: error.errmsg,
            duration: 2000
          })
        })
      },
      // 广告图片
      handleTbkPicBeforeRemove(file, fileList) {
        // this.temp.pic = ''
      },
      // 广告图片
      handleTbkPicUploadResult(response, file, fileList) {
        console.log(response.result.data.file)
        this.temp.pic = response.result.data.file
        console.log(this.temp)
      }
    }
  }
</script>

<style scoped>
  .filter-container {
    background: #fff;
    padding: 32px 16px;
  }
  .yl-table-expand {
    font-size: 0;
  }
  .yl-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .yl-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 12.5%;
  }
</style>
